import Koa from 'koa'
import log4js from 'log4js'

log4js.configure({
  appenders: {
    cheese: {
      type: 'dateFile',
      // 根目录
      // 最终生成的文件名: 'filename' + 'pattern'
      filename: 'logs/date',
      pattern: 'yyyy-MM-dd.log',
      alwaysIncludePattern: true,
    },
  },
  categories: { default: { appenders: ['cheese'], level: 'all' } },
})

const logger = log4js.getLogger('cheese')

async function loggerMiddleware(ctx: Koa.Context, next: Koa.Next) {
  const start = Date.now()

  await next()
    .then(() => {
      const ms = Date.now() - start
      const info = `${ctx.method} ${ctx.url} - ${ms}ms`
      console.log(info)
      logger.info(info)
    })
    .catch((err) => {
      const info = `${ctx.method} ${ctx.url}\n\t${err.toString()}`
      console.log(info)
      logger.error(info)
    })
}

export default loggerMiddleware
